package pl.enigmatic.awt;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JFrame;


public class Frames {

	private Frames() {}

	public static <F extends Frame> F setNiceSize(final F f) {
		final Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
		f.setSize(screen.width / 2, screen.height - 100);
		f.setPreferredSize(f.getSize());
		f.setMinimumSize(f.getSize());
		f.setMaximumSize(f.getSize());
		return f;
	}

	public static interface WindowClosingAction {

		public void windowClosing(final WindowEvent e);
	}

	public static <F extends Frame> F setExitOnClose(final F f, final WindowClosingAction close) {
		if (f instanceof JFrame) {
			((JFrame) f).setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		}
		f.addWindowListener(new WindowListener() {

			@Override
			public void windowOpened(final WindowEvent e) {}

			@Override
			public void windowIconified(final WindowEvent e) {}

			@Override
			public void windowDeiconified(final WindowEvent e) {}

			@Override
			public void windowDeactivated(final WindowEvent e) {}

			@Override
			public void windowClosing(final WindowEvent e) {
				if (close != null) {
					close.windowClosing(e);
				}
			}

			@Override
			public void windowClosed(final WindowEvent e) {
				System.exit(0);
			}

			@Override
			public void windowActivated(final WindowEvent e) {}
		});

		return f;
	}

	public static <F extends Frame> F setExitOnClose(final F f) {
		return setExitOnClose(f, null);
	}

	public static <F extends Frame> F centerLocation(final F f) {
		final Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
		f.setLocation((screen.width - f.getWidth()) / 2, (screen.height - f.getHeight()) / 2);
		return f;
	}

	public static <F extends Frame> F resizeFullscreen(final F f) {
		final Toolkit tk = Toolkit.getDefaultToolkit();
		final Dimension screen = tk.getScreenSize();
		f.setBounds(0, 0, screen.width, screen.height);
		return f;
	}

	public static <F extends Frame> F show(final F f) {
		setNiceSize(f);
		centerLocation(f);
		setExitOnClose(f);
		f.setVisible(true);
		return f;
	}

	public static <F extends Frame> F showTest(final F f) {
		show(f);
		final Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
		f.setLocation(screen.width, 0);
		return f;
	}

	public static JFrame show(final Component main) {
		final JFrame frame = new JFrame();
		frame.setLayout(new BorderLayout());
		frame.add(main, BorderLayout.CENTER);
		main.setVisible(true);
		return show(frame);
	}

	public static JFrame showTest(final Component main) {
		return showTest(show(main));
	}
}
